
 <!DOCTYPE HTML>
<html lang="ch">
<head>
  <meta charset="UTF-8">
  
    <title>PowerShell入门 | Yuan</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="Luo Yuan">
    

    
    <meta name="description" content="PowerShell是Microsoft的任务自动化和配置管理框架，由命令行shell和相关的脚本语言组成。本文是PowerShell的入门教程。">
<meta property="og:type" content="article">
<meta property="og:title" content="PowerShell入门">
<meta property="og:url" content="http://luoyuan800.github.io/2020/12/28/powershell/index.html">
<meta property="og:site_name" content="Yuan">
<meta property="og:description" content="PowerShell是Microsoft的任务自动化和配置管理框架，由命令行shell和相关的脚本语言组成。本文是PowerShell的入门教程。">
<meta property="og:locale">
<meta property="article:published_time" content="2020-12-28T08:57:43.000Z">
<meta property="article:modified_time" content="2021-04-22T07:36:59.901Z">
<meta property="article:author" content="Luo Yuan">
<meta name="twitter:card" content="summary">

    
    <link rel="alternative" href="/atom.xml" title="Yuan" type="application/atom+xml">
    
    
    <link rel="icon" href="/img/favicon.ico">
    
    
    <link rel="apple-touch-icon" href="/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/jacman.jpg">
    
    
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/%02.css">
<link rel="stylesheet" href="/.css">

<meta name="generator" content="Hexo 5.4.0"></head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/logo.png" alt="Yuan" title="Yuan"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="Yuan">Yuan</a></h1>
				<h2 class="blog-motto">一点一滴，积累技术</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/">Home</a></li>
					
						<li><a href="/archives">Archives</a></li>
					
						<li><a href="/about">About</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:luoyuan800.github.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/2020/12/28/powershell/" title="PowerShell入门" itemprop="url">PowerShell入门</a>
  </h1>
  <p class="article-author">By
       
		<a href="/about" title="Luo Yuan" target="_blank" itemprop="author">Luo Yuan</a>
		
  <p class="article-time">
    <time datetime="2020-12-28T08:57:43.000Z" itemprop="datePublished"> Published 2020-12-28</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFPowerShell"><span class="toc-number">1.</span> <span class="toc-text">什么是PowerShell</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#PowerShell%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88"><span class="toc-number">2.</span> <span class="toc-text">PowerShell能做什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E4%B8%AAPowerShell%E4%BE%8B%E5%AD%90"><span class="toc-number">3.</span> <span class="toc-text">一个PowerShell例子</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%98%E9%87%8F"><span class="toc-number">4.</span> <span class="toc-text">变量</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-number">5.</span> <span class="toc-text">数据类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-number">5.1.</span> <span class="toc-text">基本数据类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E7%BB%84"><span class="toc-number">5.2.</span> <span class="toc-text">数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%93%88%E5%B8%8C%E8%A1%A8%EF%BC%88Hashtable%E3%80%81Dictionary%EF%BC%89"><span class="toc-number">5.3.</span> <span class="toc-text">哈希表（Hashtable、Dictionary）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-number">6.</span> <span class="toc-text">运算符</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E5%AD%A6%E8%BF%90%E7%AE%97"><span class="toc-number">6.1.</span> <span class="toc-text">数学运算</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E5%80%BC%E6%AF%94%E8%BE%83"><span class="toc-number">6.2.</span> <span class="toc-text">数值比较</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%AF%B9%E8%B1%A1"><span class="toc-number">7.</span> <span class="toc-text">创建对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%8E%A7%E5%88%B6%E9%80%BB%E8%BE%91%EF%BC%9A%E9%A1%BA%E5%BA%8F%EF%BC%8C%E9%80%89%E6%8B%A9%EF%BC%8C%E5%BE%AA%E7%8E%AF"><span class="toc-number">8.</span> <span class="toc-text">基本控制逻辑：顺序，选择，循环</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%A1%E9%81%93"><span class="toc-number">9.</span> <span class="toc-text">管道</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#PowerShell-%E8%84%9A%E6%9C%AC"><span class="toc-number">10.</span> <span class="toc-text">PowerShell 脚本</span></a></li></ol>
		
		</div>
		
		<p>PowerShell是Microsoft的任务自动化和配置管理框架，由命令行shell和相关的脚本语言组成。本文是PowerShell的入门教程。<span id="more"></span></p>
<h2 id="什么是PowerShell"><a href="#什么是PowerShell" class="headerlink" title="什么是PowerShell"></a>什么是PowerShell</h2><p>PowerShell是Microsoft的任务自动化和配置管理框架，由命令行shell和相关的脚本语言组成，可以用来管理windows或者执行脚本程序。Windows操作系统内带PowerShell，同时Linux系统也可以下载安装PowerShell，所以它也算是跨平台的框架了。</p>
<h2 id="PowerShell能做什么"><a href="#PowerShell能做什么" class="headerlink" title="PowerShell能做什么"></a>PowerShell能做什么</h2><p>在PowerShell中直接管理Windows系统只是最基础的一个功能。PowerShell是个Shell，它内部定义好了一堆命令与操作系统，特别是与文件系统交互，能够启动应用程序，甚至操纵应用程序；可以编写Shell脚本，将几个命令组合起来放到文件里执行，实现文件级的重用；PowerShell是基于.Net，所以他能够能够充分利用.Net类型和COM对象，来简单地与各种系统交互，完成各种复杂的、自动化的操作。</p>
<h2 id="一个PowerShell例子"><a href="#一个PowerShell例子" class="headerlink" title="一个PowerShell例子"></a>一个PowerShell例子</h2><p>这里有一个用PowerShell计算占用内存前十的应用并显示一个饼状图的脚本。这个脚本来自网络（<a target="_blank" rel="noopener" href="https://www.zhihu.com/question/21787232/answer/63774856%EF%BC%89%E3%80%82">https://www.zhihu.com/question/21787232/answer/63774856）。</a></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"># create new excel instance</span><br><span class="line"> $objExcel &#x3D; New-Object -comobject Excel.Application</span><br><span class="line"> $objExcel.Visible &#x3D; $True</span><br><span class="line"> $objWorkbook &#x3D; $objExcel.Workbooks.Add()</span><br><span class="line"> $objWorksheet &#x3D; $objWorkbook.Worksheets.Item(1)</span><br><span class="line"></span><br><span class="line"> # write information to the excel file</span><br><span class="line">$i &#x3D; 0</span><br><span class="line">$first10 &#x3D; (ps | sort ws -Descending | select -first 10)</span><br><span class="line">$first10 | foreach -Process &#123;$i++; $objWorksheet.Cells.Item($i,1) &#x3D; $_.name; </span><br><span class="line">$objWorksheet.Cells.Item($i,2) &#x3D; $_.ws&#125;</span><br><span class="line">$otherMem &#x3D; (ps | measure ws -s).Sum - ($first10 | measure ws -s).Sum</span><br><span class="line">$objWorksheet.Cells.Item(11,1) &#x3D; &quot;Others&quot;; </span><br><span class="line">$objWorksheet.Cells.Item(11,2) &#x3D; $otherMem</span><br><span class="line"></span><br><span class="line"># draw the pie chart</span><br><span class="line">$objCharts &#x3D; $objWorksheet.ChartObjects()</span><br><span class="line">$objChart &#x3D; $objCharts.Add(0, 0, 500, 300)</span><br><span class="line">$objChart.Chart.SetSourceData($objWorksheet.range(&quot;A1:B11&quot;), 2)</span><br><span class="line">$objChart.Chart.ChartType &#x3D; 70</span><br><span class="line">$objChart.Chart.ApplyDataLabels(5)</span><br></pre></td></tr></table></figure>

<p>在你的windows系统上打开start菜单，找到WindowsPowershel并打开它，将上面这段代码拷贝到命令行窗口中按回车键。</p>
<h2 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h2><p>PowerShell中使用 $ 作为变量的起始字符。变量名称是不区分大小写并且不需要显示指定变量类型——PowerShell会自动判断赋值的数据类型。<br>比如我们用下面这个语句创建一个变量as并且赋值一个字符串：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$aS &#x3D; ‘abc’</span><br></pre></td></tr></table></figure>

<p>变量名不区分大小写也是通过$引用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$as -eq $AS</span><br></pre></td></tr></table></figure>

<p>GetType方法可以返回变量的类型。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$as.GetType()</span><br></pre></td></tr></table></figure>

<p>从新赋值一个整数后，变量类型变成了整数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$as &#x3D; 1</span><br><span class="line">$as.GetType()</span><br></pre></td></tr></table></figure>

<p>大部分时候我们不需要在定义变量的时候指定类型，但是总是会有期望使用强类型变量来限定赋值的情况，这个时候我们可以这样定义变量：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[int]$i &#x3D; 123;</span><br><span class="line">$i &#x3D; &#39;456&#39; # 自动转换为整数456</span><br><span class="line">$i &#x3D; &#39;abc&#39; # 无法转换为数字，直接报错</span><br></pre></td></tr></table></figure>

<h2 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h2><h3 id="基本数据类型"><a href="#基本数据类型" class="headerlink" title="基本数据类型"></a>基本数据类型</h3><p>包括</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">char，</span><br><span class="line">sbyte（-128 到127），</span><br><span class="line">byte （0到255），</span><br><span class="line">int16，int32 （int），int64 （long），</span><br><span class="line">string，</span><br><span class="line">bool，</span><br><span class="line">double ，</span><br><span class="line">Single（float）, </span><br><span class="line">decimal</span><br></pre></td></tr></table></figure>
<p>要注意的是PowerShell中是用 [] 来标识数据类型。</p>
<p>定义一个32位长度的整数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$i &#x3D; [int32]123</span><br><span class="line">$i.GetType()</span><br></pre></td></tr></table></figure>

<p>定义一个64位的长整数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$i &#x3D; [long]123</span><br><span class="line">$i.GetType()</span><br></pre></td></tr></table></figure>

<p>定义一个boolean值是不能直接使用true或者false，所以你得像下面这样定义一个bool变量：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$b &#x3D; [bool]&#39;true&#39;</span><br><span class="line">$b1 &#x3D; &#39;false&#39; -as [bool]</span><br><span class="line">$b2 &#x3D; [bool]1</span><br><span class="line">$b3 &#x3D; $true</span><br><span class="line">$b4 &#x3D; $false</span><br></pre></td></tr></table></figure>

<p>类型之间可以进行转换，PowerShell中使用-as关键字来转换类型：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$i &#x3D; &#39;1234&#39; -as [int]</span><br><span class="line">$i.GetType()</span><br></pre></td></tr></table></figure>

<p>也可以使用其他语言惯用的强制转换格式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$i &#x3D; [int]&#39;1234&#39;</span><br><span class="line">$i</span><br></pre></td></tr></table></figure>

<h3 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h3><p>Powershell中的基本集合类型就是数组Array。比如我们可以直接初始化一个数组，里面可以存放各种类型的数据：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ar &#x3D; &#39;a&#39;,&#39;b&#39;,&#39;c&#39;,1,12.4</span><br><span class="line">$ar.GetType()</span><br></pre></td></tr></table></figure>
<p>如果要指定数组的类型，需要使用New-Object的方式去创建数组：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ar &#x3D; New-Objectint [] 2</span><br><span class="line">$ar[1] &#x3D; &#39;10&#39; #自动转型为整数</span><br><span class="line">$ar[0] &#x3D; 100</span><br><span class="line">$ar[0] &#x3D; &#39;www&#39; #这个会报类型转换错误</span><br></pre></td></tr></table></figure>

<p>数组上使用+=运算符可以在末尾添加上新的元素（数组长度也会增加）。</p>
<h3 id="哈希表（Hashtable、Dictionary）"><a href="#哈希表（Hashtable、Dictionary）" class="headerlink" title="哈希表（Hashtable、Dictionary）"></a>哈希表（Hashtable、Dictionary）</h3><p>Hashtable用来存放Key-value结构的数据：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$hash &#x3D; @&#123;&#39;a&#39;&#x3D;1; &#39;b&#39;&#x3D;2; &#39;c&#39;&#x3D;3&#125;</span><br><span class="line">$hash.Add(&#39;d&#39;,5)</span><br><span class="line">$hash.GetType()</span><br><span class="line">$hash</span><br></pre></td></tr></table></figure>

<h2 id="运算符"><a href="#运算符" class="headerlink" title="运算符"></a>运算符</h2><h3 id="数学运算"><a href="#数学运算" class="headerlink" title="数学运算"></a>数学运算</h3><p>PowerShell支持常用的+-运算，比如</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$i&#x3D;1;</span><br><span class="line">$i++ ##先用再加</span><br><span class="line">++$i ##先加再用</span><br><span class="line">$i-- ##先用再减</span><br><span class="line">--$i ##先减再用</span><br></pre></td></tr></table></figure>
<h3 id="数值比较"><a href="#数值比较" class="headerlink" title="数值比较"></a>数值比较</h3><p>需要注意的是数值的比较运算符不能用常规的&gt;、=、&lt;。要使用大于（-gt），大于等于（-ge），小于（-lt），小于等于（-le），等于（-eq），不等于（-ne）。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">1 -gt 0</span><br><span class="line">10 -lt 100</span><br><span class="line">11 -ge 10</span><br><span class="line">11 -ne 10</span><br><span class="line">11 -eq 11</span><br><span class="line">11 -le 11</span><br></pre></td></tr></table></figure>

<h2 id="创建对象"><a href="#创建对象" class="headerlink" title="创建对象"></a>创建对象</h2><p>PowerShell 中可以使用New-Object的模式创建对象，例如前文提到的创建指定类型和长度的数组。PowerShell中也可以直接创建C#类型的对象，有两种创建模式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># 用new的方式创建对象</span><br><span class="line"># 读取一个文件的内容（5.0之前不可用）</span><br><span class="line"> $o &#x3D; [System.IO.FileStream]::new(&#39;F:\luo.jks&#39;,&#39;Open&#39;,&#39;Read&#39;)</span><br><span class="line"> $o</span><br><span class="line"> $o.Close()</span><br><span class="line"></span><br><span class="line"># 用New-Object的方式创建对象</span><br><span class="line"># 读取一个文件的内容</span><br><span class="line"> $o &#x3D; New-Object System.IO.FileStream(&#39;F:\luo.jks&#39;,&#39;Open&#39;,&#39;Read&#39;)</span><br><span class="line"> $o</span><br><span class="line"> $o.Close()</span><br></pre></td></tr></table></figure>

<h2 id="基本控制逻辑：顺序，选择，循环"><a href="#基本控制逻辑：顺序，选择，循环" class="headerlink" title="基本控制逻辑：顺序，选择，循环"></a>基本控制逻辑：顺序，选择，循环</h2><p>既然是一种语言，那么必定会包含基本的编程控制逻辑</p>
<p>顺序代码：定义一个变量，然后使用它</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$i &#x3D; 0;</span><br><span class="line">$i +&#x3D; 1;</span><br><span class="line">echo $i;</span><br></pre></td></tr></table></figure>

<p>选择代码，也就是判断执行的代码逻辑：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">#生成一个1到6之间的随机数</span><br><span class="line">$i &#x3D; Get-Random -inputobject (1..6)</span><br><span class="line">if($i -gt 5)&#123;</span><br><span class="line">   $i-&#x3D;5;</span><br><span class="line">&#125;else&#123;</span><br><span class="line">   $i+&#x3D;5;</span><br><span class="line">&#125;</span><br><span class="line">echo $i;</span><br></pre></td></tr></table></figure>

<p>循环代码，重复执行一段代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">#生成一个10到20之间的随机数</span><br><span class="line">$i &#x3D; Get-Random -inputobject (10..20)</span><br><span class="line">while($i -gt 5)&#123;</span><br><span class="line">   echo $i;</span><br><span class="line">   $i--;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="管道"><a href="#管道" class="headerlink" title="管道"></a>管道</h2><p>脚本语言中管道（Pipeline）是很重要的一个概念，就算不会用也是需要了解一下。管道的作用是传输数据：将前一个命令的输出数据作为下一个命令的输入数据。PowerShell中的管道用 | 这个符号表示。例如我们用下面这个例子输出当前系统中运行的cmd processes：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># Where-Object要求输入一个列表，</span><br><span class="line"># 大括号中的表达式对列表的中的每个元素进行判断，</span><br><span class="line"># 进而过滤掉不符合要求的元素</span><br><span class="line"># ‘$_’ 指的列表中的元素</span><br><span class="line"></span><br><span class="line">Get-Process | Where-Object &#123;$_.Name -eq&#39;cmd&#39;&#125;</span><br></pre></td></tr></table></figure>

<p>用正则表达式查找当前目录下的文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># ‘dir’ 列出指定（默认当前文件夹）文件夹下包含的文件和文件夹</span><br><span class="line"># ‘-match’ 用来进行正则表达式匹配</span><br><span class="line"></span><br><span class="line">dir | Where-Object &#123;$_.Name -match&#39;.*android.*&#39;&#125;</span><br></pre></td></tr></table></figure>

<p>指定显示Processes的信息（不显示全部属性）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"># ‘Select-Object’ 用来选择指定的数组对象的属性并且输出</span><br><span class="line"></span><br><span class="line">Get-Process | Select-Object Name,Id</span><br></pre></td></tr></table></figure>

<h2 id="PowerShell-脚本"><a href="#PowerShell-脚本" class="headerlink" title="PowerShell 脚本"></a>PowerShell 脚本</h2><p>PowerShell的脚本文件就是包含一些列PowerShell命令的文本文件，可以在PowerShell中逐行执行。现在回到本文最开始的那个显示一个饼状图的脚本例子，让我们结合已经介绍过的基本概念来具体看看这个脚本的内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"># 通过New-Object的方法创建一个新的Excel对象</span><br><span class="line">$objExcel &#x3D; New-Object -comobject Excel.Application</span><br><span class="line"># 设置访问权限为True</span><br><span class="line">$objExcel.Visible &#x3D; $True</span><br><span class="line"># 在Excel中增加一个新工作表（默认打开的excel是空的）</span><br><span class="line">$objWorkbook &#x3D; $objExcel.Workbooks.Add()</span><br><span class="line"># 创建一个sheet （Excel中的单表格概念）</span><br><span class="line">$objWorksheet &#x3D; $objWorkbook.Worksheets.Item(1)</span><br><span class="line"># 下面通过管道将process的命令传给Excel</span><br><span class="line"></span><br><span class="line">$i &#x3D; 0</span><br><span class="line"># 通过管道在命令间传输数据</span><br><span class="line"># ‘ps’ 命令获取进程的列表</span><br><span class="line"># ‘sort’ 命令根据内存占用大小对进程进行降序排序</span><br><span class="line"># ‘select’ 命令选择前10个进程</span><br><span class="line">$first10 &#x3D; (ps | sort ws -Descending | select -first 10)</span><br><span class="line"># 通过‘foreach’将数据逐个写入到表格中</span><br><span class="line">$first10 | </span><br><span class="line">    foreach -Process &#123;</span><br><span class="line">        $i++; </span><br><span class="line">        $objWorksheet.Cells.Item($i,1) &#x3D; $_.name;</span><br><span class="line">        $objWorksheet.Cells.Item($i,2) &#x3D; $_.ws</span><br><span class="line">    &#125; </span><br><span class="line">$objWorksheet.Cells.Item($i,2) &#x3D; $_.ws&#125;</span><br><span class="line"># 将其他进程占用的内存汇总为一个数据</span><br><span class="line">$otherMem &#x3D; (ps | measure ws -s).Sum - ($first10 | measure ws -s).Sum</span><br><span class="line"># 将其他进程占用的内存写入表格</span><br><span class="line">$objWorksheet.Cells.Item(11,1)&#x3D;&quot;Others&quot;;</span><br><span class="line">$objWorksheet.Cells.Item(11,2)&#x3D;$otherMem</span><br><span class="line"></span><br><span class="line"># 下面开始绘制Excel表格</span><br><span class="line"># 首先获取一个表格图表绘制对象</span><br><span class="line">$objCharts &#x3D; $objWorksheet.ChartObjects()</span><br><span class="line"># 新建一个新的的图表</span><br><span class="line">$objChart &#x3D; $objCharts.Add(0, 0, 500, 300)</span><br><span class="line"># 给这图表指定源数据</span><br><span class="line">$objChart.Chart.SetSourceData($objWorksheet.range(&quot;A1:B11&quot;), 2)</span><br><span class="line"># 指定图表的类型</span><br><span class="line">$objChart.Chart.ChartType &#x3D; 70</span><br><span class="line"># 显示</span><br><span class="line">$objChart.Chart.ApplyDataLabels(5)</span><br></pre></td></tr></table></figure>
<p>将这个脚本保存到一个文本文件中，并且命名为Top10MemChart.ps1。这样这个脚本就可以在安装有PowerShell的电脑上执行了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">.\Top10MemChart.ps1</span><br></pre></td></tr></table></figure>

<p>如果抛出脚本不能执行的错误（配置上禁止执行脚本），那么可以执行下面这个命令修改配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># 当前登陆用户可以执行脚本</span><br><span class="line">Set-ExecutionPolicy-ExecutionPolicyRemoteSigned-ScopeCurrentUser</span><br></pre></td></tr></table></figure>  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/%E7%BC%96%E7%A8%8B-%E5%B7%A5%E5%85%B7/">编程-工具</a>
</div>


</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://luoyuan800.github.io/2020/12/28/powershell/" data-title="PowerShell入门 | Yuan" data-tsina="" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2021/01/30/tensorflow/" title="浅尝TensorFlow">
  <strong>上一篇：</strong><br/>
  <span>
  浅尝TensorFlow</span>
</a>
</div>


<div class="next">
<a href="/2020/09/28/jdk14/"  title="JDK14的新特性">
 <strong>下一篇：</strong><br/> 
 <span>JDK14的新特性
</span>
</a>
</div>

</nav>

	



</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFPowerShell"><span class="toc-number">1.</span> <span class="toc-text">什么是PowerShell</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#PowerShell%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88"><span class="toc-number">2.</span> <span class="toc-text">PowerShell能做什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E4%B8%AAPowerShell%E4%BE%8B%E5%AD%90"><span class="toc-number">3.</span> <span class="toc-text">一个PowerShell例子</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%98%E9%87%8F"><span class="toc-number">4.</span> <span class="toc-text">变量</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-number">5.</span> <span class="toc-text">数据类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-number">5.1.</span> <span class="toc-text">基本数据类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E7%BB%84"><span class="toc-number">5.2.</span> <span class="toc-text">数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%93%88%E5%B8%8C%E8%A1%A8%EF%BC%88Hashtable%E3%80%81Dictionary%EF%BC%89"><span class="toc-number">5.3.</span> <span class="toc-text">哈希表（Hashtable、Dictionary）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-number">6.</span> <span class="toc-text">运算符</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E5%AD%A6%E8%BF%90%E7%AE%97"><span class="toc-number">6.1.</span> <span class="toc-text">数学运算</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E5%80%BC%E6%AF%94%E8%BE%83"><span class="toc-number">6.2.</span> <span class="toc-text">数值比较</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%AF%B9%E8%B1%A1"><span class="toc-number">7.</span> <span class="toc-text">创建对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%8E%A7%E5%88%B6%E9%80%BB%E8%BE%91%EF%BC%9A%E9%A1%BA%E5%BA%8F%EF%BC%8C%E9%80%89%E6%8B%A9%EF%BC%8C%E5%BE%AA%E7%8E%AF"><span class="toc-number">8.</span> <span class="toc-text">基本控制逻辑：顺序，选择，循环</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%A1%E9%81%93"><span class="toc-number">9.</span> <span class="toc-text">管道</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#PowerShell-%E8%84%9A%E6%9C%AC"><span class="toc-number">10.</span> <span class="toc-text">PowerShell 脚本</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/categories/杂物-医学/" title="杂物-医学">杂物-医学<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-Java/" title="编程-Java">编程-Java<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-Linux-Unix/" title="编程-Linux/Unix">编程-Linux/Unix<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-工具/" title="编程-工具">编程-工具<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-网络协议/" title="编程-网络协议">编程-网络协议<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/网站-开发/" title="网站-开发">网站-开发<sup>2</sup></a></li>
		  
		
		</ul>
</div>


  

  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=&verifier=&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m Luo Yuan in Zhuhai. <br/>
			Here is my place for knowledge accumulation.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2021 
		
		<a href="/about" target="_blank" title="Luo Yuan">Luo Yuan</a>
		
		
		</p>
</div>
</footer>
    <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<script src="/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>











<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/img/scrollup.png"/></a>
	</div>
	<script src="/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
